/**
 * \license
 * Copyright Lassi Marttala 2013
 * 
 * This file is part of dlt2jpa.
 *
 * dlt2jpa is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dlt2jpa is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with dlt2jpa.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.fizzl.dlt.message.parser;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import net.fizzl.dlt.message.DltExtendedHeader;

public class DltExtendedHeaderParser {

	public DltExtendedHeader fromByteArray(byte[] data) {
		DltExtendedHeader ret = new DltExtendedHeader();
		ByteBuffer buf = ByteBuffer.wrap(data);
		
		byte attributes = buf.get();
		ret.setVerboseMode((0 != (attributes & bmVerbose)));
		ret.setMessageType(attributes & bmMessageType);
		ret.setMessageTypeInfo(attributes & bmMessageTypeInfo);
		ret.setNumberOfArguments(buf.get());
		
		byte apid[] = new byte[5];
		apid[0] = buf.get();
		apid[1] = buf.get();
		apid[2] = buf.get();
		apid[3] = buf.get();
		apid[4] = 0;
		try {
			ret.setApplicationId(new String(apid, "US-ASCII"));
		} catch (UnsupportedEncodingException e) {
			ret.setApplicationId("!!!!");
		}
		
		byte ctid[] = new byte[5];
		ctid[0] = buf.get();
		ctid[1] = buf.get();
		ctid[2] = buf.get();
		ctid[3] = buf.get();
		ctid[4] = 0;
		try {
			ret.setContextId(new String(apid, "US-ASCII"));
		} catch (UnsupportedEncodingException e) {
			ret.setContextId("!!!!");
		}

		ret.setLength(buf.position());
		return ret;
	}
	
	// Bitmasks for header interpretation
	static final int bmVerbose 			= 0b00000001;
	static final int bmMessageType 		= 0b00001110;
	static final int bmMessageTypeInfo 	= 0b11110000;
}
